package com.sds.replicator.transformers;

import org.apache.commons.lang.StringUtils;

import java.io.UnsupportedEncodingException;

public class HTMLTransformer implements Transformer {

    private String localPath;

    public HTMLTransformer(String localPath) {
        this.localPath = localPath;

    }

    @Override
    public String getContentType() {
        return "text/html";
    }

    @Override
    public byte[] transformContent(String encoding, byte[] content) throws UnsupportedEncodingException {
        String s = new String(content,encoding);
        s = s.replaceAll("href=\"", "href=\"" + localPath + "?url=");
        s = s.replaceAll("href=\\\\\"", "href=\\\\\"" + localPath + "?url=");
        s = s.replaceAll("action=\"", "action=\"" + localPath + "?url=");
        s = s.replaceAll("src=\"/", "src=\"" + localPath + "?url=/");
        s = s.replaceAll("src=\"h", "src=\"" + localPath + "?url=h");
        s = s.replaceAll("URL=", "URL=" + localPath + "?url=");
        s = s.replaceAll("\"src\":\"", "\"src\":\"" + localPath + "?url=");
        s = s.replaceAll("base:\"http:", "base:\"" + localPath + "?url=http:");
        s = StringUtils.replace(s, ":\\\"\\\\\\/ajax\\\\\\/", ":\\\"\\\\\\" + localPath + "?url=\\\\\\/ajax\\\\\\/");
        s = StringUtils.replace(s, "domain:\"http:", "domain:\"/" + localPath + "?url=http:");
        s = StringUtils.replace(s, "\"\\/ajax\\/", "\"http:\\/\\/fb-connect-vn.appspot.com\\" + localPath + "?url=\\/ajax\\/");
        return s.getBytes(encoding);
    }

}
